﻿using System.Collections.Generic;
using System.Threading;

namespace PS_WSSDeploy_Package.Utils
{
    public interface IWdTask
    {
        void TaskExecute();
    }

    public class TaskQueue
    {
        private readonly Queue<IWdTask> queue = new Queue<IWdTask>();
        public void Enqueue(IWdTask task)
        {
            lock (queue)
            {
                queue.Enqueue(task);
                if (queue.Count == 1) RunTaskInThreadPool();
            }
        }
        public void Clear()
        {
            lock (queue)
            {
                queue.Clear();
            }
        }
        private void RunTaskInThreadPool()
        {
            ThreadPool.QueueUserWorkItem(Execute);
        }
        private void Execute(object state)
        {
            IWdTask task = null;
            lock (queue)
            {
                if (queue.Count > 0)
                    task = queue.Peek();
            }

            if (task != null)
            {
                task.TaskExecute();
            }
            lock (queue)
            {
                if (queue.Count > 0)
                {
                    queue.Dequeue();
                }
                if (queue.Count > 0)
                {
                    RunTaskInThreadPool();
                }
            }
        }
    }
}
